const http = require("http"),
  https = require("https"),
  fs = require("fs"),
  httpProxy = require("http-proxy"),
  tls = require("tls"),
  webconfig = require("./webconfig"),
  websites = webconfig.sites.filter((t) => t.enable == true),
  httpWebsites = websites.filter((t) => t.http == true),
  httpsWebsites = websites.filter((t) => t.https == true);

if (websites.length == 0) {
  return console.log("没有开启任何一个站点,请配置webconfig.js文件");
}
// 新建一个代理 Proxy Server 对象
let proxy = httpProxy.createProxyServer({ secure: false });

// 捕获异常
proxy.on("error", function (err, req, res) {
  console.log(err);
  res.writeHead(500, { "Content-Type": "text/plain" });
  res.end("Something went wrong. And we are reporting a custom error message.");
});
function app(req, res) {
  try {
    // 在这里可以自定义你的路由分发
    let host = req.headers.host || "",
      ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
    if (host.indexOf(":") != -1) {
      host = host.substr(0, host.indexOf(":"));
    }
    ip = ip ? ip.replace("::ffff:", "") : "";
    let web = websites.find((w) => w.host == host);
    if (web && (web.http || web.https)) {
      req.headers.host = web.host;
      console.log("web.target", web.target);
      // console.log(req.method,new Date().toLocaleString(),ip,host,req.url);
      // console.log(req.headers);
      proxy.web(req, res, { target: web.target });
    } else {
      console.log(
        "host not found",
        req.method,
        new Date().toLocaleString(),
        ip,
        host,
        req.url
      );
      res.writeHead(200, { "Content-Type": "text/plain" });
      res.end("Welcome to my server! " + host);
    }
  } catch (e) {
    console.log(e);
  }
}
// 另外新建一个 HTTP 80 端口的服务器，也就是常规 Node 创建 HTTP 服务器的方法。
// 在每次请求中，调用 proxy.web(req, res config) 方法进行请求分发
if (httpWebsites.length > 0) {
  http.createServer(app).listen(webconfig.port.http, function () {
    console.log("Http server listening on ", webconfig.port.http);
  });
}

if (httpsWebsites.length > 0) {
  //多个二级域名SSL验证
  let tls = require("tls");
  let KeyCerts = {};
  let SSLKey_default = "",
    SSLCert_default = "";
  httpsWebsites.forEach((t) => {
    KeyCerts[t.host] = tls.createSecureContext({
      key: fs.readFileSync("./ssl/" + t.host + ".key", "utf8"),
      cert: fs.readFileSync("./ssl/" + t.host + ".crt", "utf8"),
      rejectUnauthorized: false,
    });
    if (!SSLKey_default) {
      SSLKey_default = fs.readFileSync("./ssl/" + t.host + ".key", "utf8");
      SSLCert_default = fs.readFileSync("./ssl/" + t.host + ".crt", "utf8");
    }
  });
  let getKeyCert = {
    SNICallback: function (domain, cb) {
      if (KeyCerts[domain]) {
        if (cb) {
          cb(null, KeyCerts[domain]);
        } else {
          return KeyCerts[domain]; //兼容Node老版本
        }
      } else {
        //一定要设置默认值，这样访问xyz.comecode.net时，也可以访问，只是会有安全性提示
        if (cb) {
          cb(null, KeyCerts["www.xiaoshuicao.com"]);
        } else {
          return KeyCerts["www.xiaoshuicao.com"];
        }
      }
    },
    key: SSLKey_default,
    cert: SSLCert_default,
    rejectUnauthorized: false,
  };

  https.createServer(getKeyCert, app).listen(webconfig.port.https, function () {
    console.log("Http server listening on ", webconfig.port.https);
  });
}
